package org.funtester.performance.books.chapter11.section4;

import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 全局唯一标识符工具类,提供UUID、雪花算法、线程独立变量、原子操作类的唯一标识符
 */
public class UniqueUtils {

    private static SnowflakeWorker SNOW_WORKER;// 雪花算法对象

    private static long origin = 1000000000000000000L;// 起始值

    private static ThreadLocal<Long> EXCLUSIVE = new ThreadLocal<Long>() {// 线程独立变量
        @Override
        protected Long initialValue() {// 初始化值
            return 0L;
        }
    };

    private static AtomicLong ATOMIC = new AtomicLong(0);// 原子计数器

    static {// 静态代码块
        SNOW_WORKER = new SnowflakeWorker(1, 1);// 初始化雪花算法对象
    }

    /**
     * 获取雪花算法的唯一标识符
     *
     * @return
     */
    public static String getSnowMark() {
        return String.valueOf(SNOW_WORKER.nextId());
    }

    /**
     * 获取UUID唯一标识符
     *
     * @return
     */
    public static String getUUID() {
        return UUID.randomUUID().toString();
    }

    /**
     * 获取线程独立变量的唯一标识符
     *
     * @return
     */
    public static String getExclusiveMark() {
        Long l = EXCLUSIVE.get();
        EXCLUSIVE.set(l + 1);
        return String.valueOf(l + origin);
    }

    /**
     * 获取原子操作类的唯一标识符
     *
     * @return
     */
    public static String getAtomicMark() {
        return String.valueOf(ATOMIC.getAndIncrement() + origin);
    }


}
